﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IService;
using Data;
using IData;
using Model;
using System.Data;
using System.Data.SqlClient;

namespace Service
{
   public class CheckService:ICheckService
    {
       string sql;
       public CheckService()
       {
           sql = string.Empty;
           
       }
       /// <summary>
       /// 创建新会员
       /// </summary>
       /// <returns></returns>
       public bool InsertLogin(MemberModel model)
       {     
           //调用MD5加密
           IPasswordService pwd = new PasswordService();
           string time = DateTime.Now.ToString("yyyyMMdd");
          string mdpwd=pwd.MD5Encrypt(model.password,model.Skey);
          //创建sql字符连接
          StringBuilder sqlValues = new StringBuilder();
          StringBuilder sqlNames = new StringBuilder();
          Type t = model.GetType();
          //遍历model属性
          foreach (var item in t.GetProperties())
          {
              if (item.Name != "password")
              {
                  //获取name
                  string name = item.Name;
                  object value = item.GetValue(model, null);//获取值
                  sqlNames.Append( name + ",");
                  sqlValues.Append("'" + value + "',");
              }
          }
         string sql1=sqlNames.ToString();
         string sql2 = sqlValues.ToString();
         //拼接sql语句
         string sql = "insert into HouseKeeping_Member (" + sql1 + "EncryptedString) values(" + sql2+"'"+mdpwd+"')";
         //执行sql语句
          IDbLogin a = new DbLogin();
         int count= a.add(sql);
         bool result;
         if (count > 0)
         {
             result = true;
         }
         else { result = false; }
         return result;
       }
       /// <summary>
       /// 检查登录账户密码
       /// </summary>
       /// <param name="userName">用户名</param>
       /// <param name="pwd">未加密密码</param>
       /// <returns></returns>
       public bool CheckLogin(string userName, string pwd)
       {
           string sql = string.Empty;
           sql="select Skey from HouseKeeping_Member where LoginName='"+userName+"'";
           //执行sql语句
           IDbLogin a = new DbLogin();
            DataTable dt=a.select(sql);
           string skey = dt.Rows[0]["Skey"].ToString();
           IPasswordService pwds = new PasswordService();
           string encryptedString = pwds.MD5Encrypt(pwd, skey);
           //bool returnValue = a.selectBool("EXEC dbo.checkpassword '" + encryptedString + "','" + userName + "'");
           bool returnValue = a.selectBool("dbo.checkpassword", new SqlParameter("EncryptedString", encryptedString), new SqlParameter("LoginName", userName));
           return returnValue;

       }


    }
}
